//
//  HJOAuthController.m
//  newOcWeibo
//
//  Created by heJing on 15/7/27.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import "HJOAuthController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "HJAccount.h"
#define HM_REQUEST_TOKEN_BEASE_URL @"https://api.weibo.com/oauth2/authorize"
#define HM_CLIENT_ID @"839300887"
#define HM_SECRET @"2ad1b3e3e376b28e8ae7fdcdabc3ea49"
#define HM_REDIRECT_URL @"http://www.baidu.com"
#define HM_ACCESSTOKEN_URL @"https://api.weibo.com/oauth2/access_token"

@interface HJOAuthController ()<UIWebViewDelegate>

- (IBAction)close:(UIBarButtonItem *)sender;

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation HJOAuthController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    // 1.从新浪服务器加载登陆界面(获取未授权的RequestToken)
    NSString *str = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@", HM_REQUEST_TOKEN_BEASE_URL, HM_CLIENT_ID, HM_REDIRECT_URL];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];

}

- (IBAction)close:(UIBarButtonItem *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    // 1.判断即将要请求的地址中是否包含code= ,如果包含证明已经授权成功, 不需要继续跳转
    HJLog(@"%@", request.URL.absoluteString);

    NSRange range = [request.URL.absoluteString rangeOfString:@"code="];
    //    range.length  0  3
    //    range.location NSNotFound  1
    
    if (range.location != NSNotFound) {
        HJLog(@"已经获取到了授权的RequestToken");
        // 2.截取已经授权的RequestToken, 然后后利用RequestToken换取AccessToken
        HJLog(@"%@", request.URL.query);
        NSString *code = [request.URL.query substringFromIndex:@"code=".length];
        HJLog(@"%@", code);
        // 3.利用code换取AccessToken
        [self accessTokenWithCode:code];
        return NO;
    }
    return YES;

}

- (void)accessTokenWithCode:(NSString *)code{

    // 1.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"client_id"] = HM_CLIENT_ID;
    parameters[@"client_secret"] = HM_SECRET;
    parameters[@"grant_type"] = @"authorization_code";
    parameters[@"code"] = code;
    parameters[@"redirect_uri"] = HM_REDIRECT_URL;
    
    // 2.获取网络管理者
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    // 2.1设置AFN支持的类型
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    // 3.发送请求
    [manger POST:HM_ACCESSTOKEN_URL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

        HJLog(@"--->%@", responseObject);
        // 3.1.将字典转换为模型
        HJAccount *account = [HJAccount accountWithDict:responseObject];

        // 3.2 归档数据
        [account save];
        
        // 3.3 显示新特性控制器选择
        [[UIApplication sharedApplication].keyWindow chooseRootViewController];

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        HJLog(@"%@", error);
        [SVProgressHUD showWithStatus:@"请求失败" maskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD dismiss];

    }];
}


- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"正在加载, 请不要猴急...!!!" maskType:SVProgressHUDMaskTypeBlack];

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];

}


@end
